//
//  M1FileUpload.m
//  NewMarryU
//
//  Created by apple on 2018/7/19.
//  Copyright © 2018年 Cedar. All rights reserved.
//

#import "M1FileUpload.h"
#import <AdSupport/AdSupport.h>

@interface M1FileUpload()
@property (nonatomic, assign) NSUInteger m1_imageCount;
@property (nonatomic, strong) NSMutableArray *m1_pictures;
@property (nonatomic, strong) NSMutableArray *m1_urls;
@property (nonatomic, assign) NSInteger m1_dataLength;
@property (nonatomic, assign) NSInteger m1_totalLength;
@property (nonatomic, strong) NSMutableDictionary *m1_tasks;
@end

@implementation M1FileUpload
+ (instancetype)manager
{
    static M1FileUpload *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!instance)
        {
            instance = [[M1FileUpload alloc] init];
        }
    });
    return instance;
}

-(void)m1_uploadImages:(NSArray * _Nullable)images progress:(void(^)(CGFloat progress))progress completion:(void(^)(NSArray <NSString *>* _Nullable urls,NSArray <NSDictionary *>* _Nullable pictures ,NSError * _Nullable error))completion{
    
    if (images.count ==0) {
        completion(nil,nil,[[NSError alloc] initWithDomain:@"12123" code:-10086 userInfo:@{NSLocalizedDescriptionKey:@"数组为空"}]);
        return;
    }
    
    NSMutableArray *m1_datas = [NSMutableArray array];
    id image = images.firstObject;
    if ([image isKindOfClass:[NSData class]])
    {
        m1_datas = [(NSArray <NSData *> *)images mutableCopy];
    }
    else if ([image isKindOfClass:[UIImage class]])
    {
        for (int i = 0; i < images.count; i++) {
            [m1_datas addObject:UIImageJPEGRepresentation((UIImage *)[images objectAtIndex:i], 0.6)];
        }
    }
    self.m1_imageCount = 0;
    self.m1_pictures = [[NSMutableArray alloc] init];
    self.m1_urls = [[NSMutableArray alloc] init];
    self.m1_tasks = [[NSMutableDictionary alloc] init];
    self.m1_totalLength = 0;
    for (NSData *imageData in m1_datas)
    {
        self.m1_totalLength += [imageData length];
    }
    
    [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].delegate.window animated:YES];
    [self m1_uploadImageDatas:m1_datas progress:progress completion:completion];
}

- (void)m1_uploadImageDatas:(NSArray <NSData *> * _Nullable)imageDatas progress:(nullable void (^)(CGFloat progress))progress completion:(nullable void (^)(NSArray <NSString *> * _Nullable urls, NSArray <NSDictionary *> * _Nullable pictures, NSError * _Nullable error))completion{
    if (self.m1_imageCount < imageDatas.count) {
        NSData *m1_imageData = [imageDatas objectAtIndex:self.m1_imageCount];
        AFHTTPSessionManager *m1_sessionManager = [AFHTTPSessionManager manager];
        [m1_sessionManager.requestSerializer setValue:@"richpeople" forHTTPHeaderField:@"channel"];
        NSURLSessionDataTask *m1_sessionTask = [m1_sessionManager POST:@"http://img.51marryyou.com/upload.php" parameters:nil constructingBodyWithBlock:^(id <AFMultipartFormData> _Nonnull formData) {
            long long interval = [[NSDate date] timeIntervalSince1970] * 1000;
            NSString *imageTypeString = @"jpg";
            NSString *fileName = [NSString stringWithFormat:@"image%lu_%lld.%@", self.m1_imageCount, interval, imageTypeString];
            [formData appendPartWithFileData:m1_imageData name:@"images" fileName:fileName mimeType:@"image/jpg"];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            CGFloat m1_progress = uploadProgress.fractionCompleted;
            float uploadedProgress = 0;
            if (self.m1_totalLength > 0) {
                uploadedProgress = self.m1_totalLength * 1.0 / self.m1_totalLength;
                NSData *uploadingImageData = [self.m1_tasks objectForKey:self.m1_tasks.allKeys.lastObject];
                if (uploadingImageData.length) {
                    uploadedProgress = uploadedProgress + uploadingImageData.length * m1_progress / self.m1_totalLength;
                }
                else {
                    uploadedProgress = uploadedProgress + (1 - uploadedProgress) / (imageDatas.count - self.m1_imageCount) * m1_progress;
                }
            }
            else {
                uploadedProgress = 1;
            }
            uploadedProgress = MAX(uploadedProgress, 0);
            uploadedProgress = MIN(uploadedProgress, 1);
            dispatch_async(dispatch_get_main_queue(), ^{
                progress(uploadedProgress);
            });
        } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
            NSData *data = [self.m1_tasks objectForKey:@(task.taskIdentifier)];
            self.m1_dataLength += data.length;
            self.m1_imageCount++;
            NSString *url = nil;
            id jsonData = responseObject;
            if ([jsonData isKindOfClass:[NSDictionary class]])
            {
                NSDictionary *dicJsonData = (NSDictionary *)jsonData;
                url = dicJsonData[@"item"];
                [self.m1_urls addObject:url];
                CGSize size = [UIImage imageWithData:data].size;
                NSDictionary *dict = @{@"pic":url,@"size":[NSString stringWithFormat:@"%dx%d", (int)size.width, (int)size.height],@"color":@"FFFFFF"};
                [self.m1_pictures addObject:dict];
            }
            [self m1_uploadImageDatas:imageDatas progress:progress completion:completion];
            if (self.m1_imageCount == imageDatas.count) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].delegate.window animated:NO];
                    completion(self.m1_urls, self.m1_pictures, nil);
                });
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].delegate.window animated:NO];
                completion(nil, nil, error);
            });
        }];
        [self.m1_tasks setObject:m1_imageData forKey:@(m1_sessionTask.taskIdentifier)];
    }
}

@end
